package com.learning.security.generator;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.builder.CustomFile;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class CustomerTemplateEngine extends FreemarkerTemplateEngine {

    @Override
    protected void outputCustomFile(List<CustomFile> customFiles, TableInfo tableInfo, Map<String, Object> objectMap) {
        // 重新通过表名获取类名 最终去除了表名的前缀、后缀、驼峰
        // 如果使用tableInfo.getName()获取类名，因在配置文件中对entity添加了后缀DO, 则在定义其他比如VO、DTO等文件时，会带着DO
        String entityName = getConfigBuilder().getStrategyConfig().entity().getNameConvert().entityNameConvert(tableInfo);

        String parentPath = getPathInfo(OutputFile.parent);
        customFiles.forEach(file -> {
            String otherPackageName = getConfigBuilder().getPackageConfig().joinPackage(file.getPackageName());
            objectMap.put("otherPackageName", otherPackageName);
            Function<TableInfo, String> formatNameFunction = file.getFormatNameFunction();
            String otherClassName = null != formatNameFunction ? entityName + formatNameFunction.apply(tableInfo) : entityName;
            objectMap.put("otherEntityName", otherClassName);

            String filePath = StringUtils.isNotBlank(file.getFilePath()) ? file.getFilePath() : parentPath;
            if (StringUtils.isNotBlank(file.getPackageName())) {
                filePath = filePath + File.separator + file.getPackageName().replaceAll("\\.", StringPool.BACK_SLASH + File.separator);
            }
            String fileName = filePath + File.separator + (null != formatNameFunction ? entityName + formatNameFunction.apply(tableInfo) : entityName) + file.getFileName();
            outputFile(new File(fileName), objectMap, file.getTemplatePath(), file.isFileOverride());
        });
    }

    @Override
    protected void outputController(TableInfo tableInfo, Map<String, Object> objectMap) {
        String entityName = getConfigBuilder().getStrategyConfig().entity().getNameConvert().entityNameConvert(tableInfo);
        objectMap.put("baseControllerPath", toLowerCaseFirstOne(entityName));
        super.outputController(tableInfo, objectMap);
    }

    /**
     * 首字母转为小写
     *
     * @param s
     * @return
     */
    private String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0))) {
            return s;
        } else {
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }
}
